package com.yz.admin.login.controller;

import com.yz.admin.login.pojos.User;
import com.yz.admin.login.service.impl.UserServiceImpl;
import com.yz.admin.login.vo.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.xml.ws.Action;

@Controller
@RequestMapping("/login")
public class UserController {
@Autowired
private UserServiceImpl userService;

    @RequestMapping("/login")
    @ResponseBody
    public Result login(String phone, String password){
        UsernamePasswordToken token = new UsernamePasswordToken(phone,password);
        try {
            SecurityUtils.getSubject().login(token);
            return new Result(true,"登陆成功");
        }catch(Exception e){
            e.printStackTrace();
            return new Result(false,"账号或密码错误");
        }
    }

    @RequestMapping("/logout")
    public String logout() {
        SecurityUtils.getSubject().logout();
        //退出操作成功后，做了重定向的操作访问是一个 完全不存在的请求。
        return "redirect:/welcome";//这个重定向的请求可以写任何url，但是不能写被shiro进行了anon的请求
    }


    @RequestMapping("/regist")
    @ResponseBody
    public Result register(String phone,String password) {
        User user = new User();
        user.setPassword(password);
        user.setPhone(phone);
        try {
            userService.save(user);
            return new Result(true, "注册成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "注册失败");
        }
    }
}
